<template>
  <div class="requestAdd">
    <!-- 筛选按钮 -->
    <div class="search-button">
      <el-button class="btn search" @click="getrealinvent"
        ><el-icon class="icon" color="#fff"> <Search /> </el-icon
        >查询</el-button
      >
      <el-button class="btn add" @click="handleRefresh"
        ><el-icon class="icon" color="#fff"> <Refresh /> </el-icon
        >重置</el-button
      >
      <el-button class="btn save" @click="handleExport()"
        ><el-icon class="icon" color="#fff"> <Download /> </el-icon
        >导出列表</el-button
      >
    </div>
    <!-- 筛选条件 -->
    <div class="search">
      <div class="search-item">
        <el-select
          v-model="params.fileType"
          placeholder="请选择文档类型"
          clearable
          class="search-input"
        >
          <el-option
            v-for="dict in contractList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />

       
        </el-select>
      </div>
      <div class="search-item">
        <el-date-picker
          v-model="time"
          type="daterange"
          align="right"
          range-separator="至"
          start-placeholder="更新开始日期"
          end-placeholder="结束日期"
          format="YYYY/MM/DD"
          value-format="YYYY-MM-DD"
        />
      </div>
      <div class="search-item">
        <el-input
          clearable
          v-model="params.contractCode"
          class="search-input"
          placeholder="请输入文件名称/合同编号"
        ></el-input>
      </div>
      <div class="search-item">
        <el-input
          clearable
          v-model="params.projectCode"
          class="search-input"
          placeholder="请输入项目名称/项目编号"
        ></el-input>
      </div>
    </div>

   

    <div class="tabinfo">
      <!-- 表格数据 -->
      <el-table
        v-loading="loading"
        :data="projectContractList"
        border
        height="64vh"
        :header-cell-style="{ 'text-align': 'center' }"
      >
       <!-- 操作模式 -->
       <el-table-column
          label="操作"
          :show-overflow-tooltip="true"
          width="100px"
        >
          <template #default="{ row }">
            <div class="table-operate">
              <el-icon
                v-hasPermi="['system:contract:detail']"
                title="查看详情"
                color="#007CEF"
                class="table-icon"
                :size="20"
                @click="handleOperate('detail', row)"
              >
                <Document />
              </el-icon>
              <el-icon
                v-hasPermi="['system:contract:down']"
                title="下载"
                color="#007CEF"
                class="table-icon"
                :size="20"
                @click="fileDown(row)"
              >
                <Download />
              </el-icon>
             
            </div> </template
        ></el-table-column>
        <el-table-column
          type="index"
          label="序号"
          :index="indexMethod"
          width="60"
          align="center"
        />

        <el-table-column
          label="文件分类"
          prop="fileTypeName"
          :show-overflow-tooltip="true"
          min-width="100"
        />
        
     
        <el-table-column
          label="文件名称"
          prop="name"
          :show-overflow-tooltip="true"
          min-width="120"
        >
          <template #default="{ row }">
            <span  style="color: #409eff; cursor: pointer" @click="handleOperate('detail', row)">{{ row.name ? row.name : "--" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="文件编号"
          prop="contractCode"
          :show-overflow-tooltip="true"
          min-width="120"
        >
          <template #default="{ row }">
            <span>{{ row.contractCode ? row.contractCode : "--" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="项目名称"
          prop="projectName"
          :show-overflow-tooltip="true"
          min-width="120"
        >
          <template #default="{ row }">
            <span>{{ row.projectName ? row.projectName : "--" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="合同类型"
          prop="typeName"
          :show-overflow-tooltip="true"
          min-width="120"
        >
          <template #default="{ row }">
            <span>{{ row.typeName ? row.typeName : "--" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="云盘位置"
          prop="cloudName"
          :show-overflow-tooltip="true"
          min-width="120"
        >
          <template #default="{ row }">
            <span>{{ row.cloudName ? row.cloudName : "--" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="档案柜位置"
          prop="space"
          :show-overflow-tooltip="true"
          min-width="120"
        >
          <template #default="{ row }">
            <span>{{ row.space ? row.space : "--" }}</span>
          </template>
        </el-table-column>

        
        <el-table-column
          label="更新时间"
          prop="createTime"
          :show-overflow-tooltip="true"
          min-width="100"
        />
    
        <el-table-column
          label="创建者"
          prop="userName"
          :show-overflow-tooltip="true"
          min-width="100"
        />
      </el-table>

      <!-- 分页 -->
      <pagination
        class="pagination"
        :total="total"
        v-model:page="params.pageNum"
        v-model:limit="params.pageSize"
        @pagination="getList"
      />
    </div>
  </div>
</template>

<script setup>
const { proxy } = getCurrentInstance();
import { Base64 } from "js-base64";
import {
  getProjectContractListApi,
  getFileListApi,
  getSynthesisContractListApi,
  getPurContractListApi,
} from "@/api/compact/multiple";
import { getDictsApi } from "@/api/dict";
import useUserStore from "@/store/modules/user";

const router = useRouter();
const activeName = ref("first");
//销售合同列表数据
const projectContractList = ref([]);
//项目采购列表数据
const inoutstockDtlListList = ref([]);
//综合服务合同列表数据
const comprehensiveServicesList = ref([]);

//销售类型列表
const contractList = ref([]);
//所属行业列表
const industryTypeList = ref([]);
//服务项目列表
const serviceTypeList = ref([]);
//筛选时间
let time = ref([]);
// 销售合同列表总数
const total = ref(0);
// 采购合同列表总数
const stockDtltotal = ref(0);
const sumPurchaseAmount = ref(0);
const sumSaleAmount = ref(0);
//综合服务列表总数
const comprehenServicetotal = ref(0);
// 表格加载效果
const loading = ref(false);
//当前用户信息
const userStore = useUserStore();
// 搜索参数
const originalParams = {
  startDate: null, //开始日期
  endDate: null, //结束日期
  contractCode: "", // 合同编号
  projectCode: "", // 项目编号/项目名称
  fileType: null,
  pageNum: 1,
  pageSize: 50,
};
// 将初始数据转化为响应式对象
const params = reactive({ ...originalParams });

/**
 * @description: 重置
 */
const handleRefresh = () => {
  time.value = [];
  Object.assign(params, {
    startDate: null, //开始日期
  endDate: null, //结束日期
  contractCode: "", // 合同编号
  projectCode: "", // 项目编号/项目名称
  fileType: null,
  pageNum: 1,
  pageSize: 50,
  });
  if (activeName.value === "first") {
    getList();
  } else if (activeName.value === "second") {
    getstockDtltotalList();
  } else {
    getservicesList();
  }
};
/**
 * @description: 列表查询
 */
const getrealinvent = () => {
  getList();
};

/**
 * @description: 文件下载
 * @param {Object} row  当前行数据
 */
 const fileDown = (row) => {
  // const res = fileDownload(row.url);
  // var debug = res;
  // if (debug) {
  // 创建隐藏的可下载链接  //url下载
  if (row.filePath) {
    let eleLink = document.createElement("a");
    eleLink.download = row.name;
    eleLink.style.display = "none";
    eleLink.href = row.filePath;
    // 触发点击
    document.body.appendChild(eleLink);
    eleLink.click();
    // 然后移除
    document.body.removeChild(eleLink);
  }

};

/**
 * @description: 表格操作
 * @param {String} type 类型
 * @param {Object} row  当前行数据
 */
 const handleOperate = async (type, row) => {
  switch (type) {
    case "detail":
      let docUrl = row.filePath;
      let url = encodeURIComponent(Base64.encode(docUrl));
      let officeUrl = "http://101.71.158.60:50098/onlinePreview?url=" + url+ '&watermarkTxt=' + encodeURIComponent(userStore.nickName);; // 在新窗口打开编码后的链接
      window.open(officeUrl, "_target");
      break;

    default:
      break;
  }
};
// watch(activeName, (newValue, oldValue) => {
//   // 监听tab变化时将筛选条件数据恢复至原始数据
//   time.value = [];
//   params.startDate = null;
//   params.endDate = null;
//   Object.keys(originalParams).forEach((key) => {
//     params[key] = originalParams[key];
//   });

//   if (newValue === "first") {
//     getList();
//   } else if (newValue === "second") {
//     getstockDtltotalList();
//   } else {
//     getservicesList();
//   }
// });
/**
 * @description: 获取项目销售合同列表
 */
const getList = async () => {
  try {
    loading.value = true;
    let { pageNum, pageSize } = params;
    if (time.value != null && time.value.length > 0) {
      params.startDate = time.value[0];
      params.endDate = time.value[1];
    } else {
      params.startDate = null;
      params.endDate = null;
    }
    const res = await getFileListApi({ pageNum, pageSize }, params);
    projectContractList.value = res.list.rows;
    sumPurchaseAmount.value = res.sumPurchaseAmount;
    sumSaleAmount.value = res.sumSaleAmount;

    console.log(res);
    total.value = res.list.total;
    loading.value = false;
  } catch {
    loading.value = false;
  }
};
/**
 * @description: 获取项目采购列表
 */

const getstockDtltotalList = async () => {
  try {
    loading.value = true;
    let { pageNum, pageSize } = params;
    if (time.value != null && time.value.length > 0) {
      params.startDate = time.value[0];
      params.endDate = time.value[1];
    } else {
      params.startDate = null;
      params.endDate = null;
    }
    params.masterContractType = 2; //列表固定参数
    const res = await getPurContractListApi({ pageNum, pageSize }, params);
    inoutstockDtlListList.value = res.rows;
    stockDtltotal.value = res.total;
    loading.value = false;
  } catch {
    loading.value = false;
  }
};
/**
 * @description: 获取综合服务合同列表
 */

const getservicesList = async () => {
  try {
    loading.value = true;
    let { pageNum, pageSize } = params;
    if (time.value != null && time.value.length > 0) {
      params.startDate = time.value[0];
      params.endDate = time.value[1];
    } else {
      params.startDate = null;
      params.endDate = null;
    }
    const res = await getSynthesisContractListApi(
      { pageNum, pageSize },
      params
    );
    comprehensiveServicesList.value = res.rows;
    comprehenServicetotal.value = res.total;
    loading.value = false;
  } catch {
    loading.value = false;
  }
};

/**
 * @description: 处理导出
 * @param {String} flag 1.列表 2.明细列表
 */
const handleExport = async () => {
  console.log("daochu", activeName.value);
  // 日期
  const currentDate = new Date();
  const year = currentDate.getFullYear();
  let month = currentDate.getMonth() + 1; // 月份是从 0 开始计数的，因此要加1
  if (month < 10) {
    month = "0" + month;
  }
  const day = currentDate.getDate();
  let date = year + "" + month + "" + day;
  // 随机数
  let randomNum = Math.floor(Math.random() * (999 - 100 + 1) + 100);
  // 用户昵称
  let userName = userStore.name;
  // 文件名
  let fileNmae = date + userName + randomNum;
  let { pageNum, pageSize } = params;
    /* 导出列表 */
    proxy.download(
      `/system/compact/exportAllFileList?pageNum=${pageNum}&pageSize=${pageSize}`,
      params,
      `${fileNmae}.xlsx`,
      null,
      1
    );
 
};
function formatContractMoney(row, column, cellValue) {
  // 判断数据是否为数字
  if (typeof cellValue === "number" && !isNaN(cellValue)) {
    // 将数据保留两位小数
    const formattedValue = cellValue.toFixed(2);
    return formattedValue;
  } else {
    // 如果数据不是数字，则原样返回
    return cellValue;
  }
}
/* 跳转营销合同详情 */
const handlecontractCodeDetail = (row) => {
  const { href } = router.resolve({
    path: `/SealManage/contract`,
    query: { contractId: row.contractId },
  });
  window.open(href, "_blank");
};
/* 跳转采购合同详情 */
const handlePurchaseDetail = (row) => {
  const { href } = router.resolve({
    path: `/SealManage/contractSeal`,
    query: { purchaseContractId: row.purchaseContractId },
  });
  window.open(href, "_blank");
};
/* 跳转销售合同/采购合同详情 */
const handleContractDetail = (row) => {
  if (row.modelTypeName === "综合服务模块") {
    const { href } = router.resolve({
      path: `/SealManage/serveContract`,
      query: { contractId: row.synthesisContractId },
    });
    window.open(href, "_blank");
  } else {
    const { href } = router.resolve({
      path: `/SealManage/contractSeal`,
      query: { purchaseContractId: row.synthesisContractId },
    });
    window.open(href, "_blank");
  }
};
/* 点击行内库存数据 */
const handleStock = async (command) => {
  const { href } = router.resolve({
    path: `/sales/project`,
    query: { projectId: command },
  });
  window.open(href, "_blank");
};
/* 跳转项目详情 */
const handleProjectDetail = (row) => {
  const { href } = router.resolve({
    path: `/sales/project`,
    query: { projectId: row[0].projectId },
  });
  window.open(href, "_blank");
};

/**
 * @description: 序号
 * @param {Number} index 索引
 */
function indexMethod(index) {
  const currentPage = params.pageNum;
  const pageSize = params.pageSize;
  const truelndex = (currentPage - 1) * pageSize + index + 1;
  return truelndex;
}
/**
 * @description: 获取字典
 */
async function getDicts() {
  // 销售类型
  await getDictsApi("erp_archive_file_type").then((res) => {
    if (res.code === 200) {
      contractList.value = res.data;
    }
  });

  // 所属行业
  await getDictsApi("erp_purchase_detail_type").then((res) => {
    if (res.code === 200) {
      industryTypeList.value = res.data.filter(
        (item) => item.value === 0 || item.value === 1
      );
    }
  });
  // 服务项目
  await getDictsApi("erp_export_detail_type").then((res) => {
    if (res.code === 200) {
      serviceTypeList.value = res.data;
    }
  });
}
onMounted(() => {
  getDicts();
  getList();
});
</script>

<style lang="scss" scoped>
.requestAdd {
  padding: 20px;
  width: 100%;
  height: 100%;
  .sum-box {
    height: 56px;
    display: flex;
    margin-bottom: 20px;
    .sum-box-item {
      width: 420px;
      height: 100%;
      background-color: #f8faff;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 20px;
    }
    .sum-text {
      color: #409eff;
      line-height: 200px;
    }
  }
  .pagination {
    margin-top: 20px;
  }
  :deep(.el-tabs__item.is-top) {
    width: 120px;

    font-size: 16px;
  }
  .image-content {
    width: 100%;
    line-height: 0px;
    overflow: auto;
  }
}
</style>
